package com.song.codesandbox.test;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.Statistics;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.song.codesandbox.CodeSandBox;
import com.song.codesandbox.model.*;
import com.song.codesandbox.utils.DockerUtils;
import com.song.codesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class JavaDockerCodeSandBox implements CodeSandBox {

    /**
     * 全局代码存放目录
     */
    private static final String GLOBAL_CODE_DIR_NAME = "TmpCode";

    /**
     * 全局代码文件名
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    /**
     * 超时时间，单位：毫秒
     */
    private static final long TIME_OUT = 5000L;

    /**
     * 镜像初始化状态
     */
    private static boolean FIRST_INIT = true;

    /**
     * 执行代码
     *
     * @param request
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();
        if (inputList == null || inputList.isEmpty() || StrUtil.isBlank(code) || StrUtil.isBlank(language)) {
            return createErrorResponse(new IllegalArgumentException("参数不合法"));
        }
        return executeCode(request.getInputList(), request.getCode(), request.getLanguage());
    }

    /**
     * 执行代码
     *
     * @param inputList 程序的输入
     * @param code      程序要执行的代码
     * @param language  编程语言
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(List<String> inputList, String code, String language) {

        /**
         * 1. 程序编译与执行的前置准备
         * - 创建用户代码编译与运行的临时目录
         */
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在，如果不存在则新建目录
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        /**
         * 2. 为用户生成独立的代码存放文件夹，将用户的代码隔离存放
         */
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        /**
         * 3. 编译代码，保存.class文件
         */
        log.info("---------代码编译开始---------");
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        log.info("编译命令: {}", compileCmd);
        ExecuteMessage compileExecuteMessage = new ExecuteMessage();
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            compileExecuteMessage = ProcessUtils.runProcess(compileProcess, ProcessExecType.COMPILE);
        } catch (IOException e) {
            return createErrorResponse(e);
        }
        log.info("---------代码编译结束---------");

        /**
         * 4. 创建容器, 将编译后的代码放入容器内
         */
        DockerClient dockerClient = DockerUtils.getDefaultDockerClient();

        String imageName = "openjdk:8-alpine";
        // 下载镜像
        if (FIRST_INIT) {
            try {
                DockerUtils.pullImage(dockerClient, imageName);
                FIRST_INIT = false;
            } catch (InterruptedException e) {
                log.error("拉取镜像异常", e);
                throw new RuntimeException(e);
            }
        }

        // 创建容器
        String containerId = DockerUtils.createContainer(dockerClient, imageName, userCodeParentPath);

        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        log.info("程序输入: {}", inputList.toString());
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            // 构造
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse =
                    dockerClient.execCreateCmd(containerId)
                            .withCmd(cmdArray)
                            .withAttachStderr(true)
                            .withAttachStdin(true)
                            .withAttachStdout(true)
                            // 执行
                            .exec();
            log.info("构建执行的cmd响应: {}", execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            long time = 0L;
            final boolean[] timeout = {true};
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    // 如果执行完成, 则没有超时
                    timeout[0] = false;
                    log.info("onComplete: 执行成功");
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    if (frame.getStreamType().equals(StreamType.STDERR)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果: " + new String(frame.getPayload()));
                        log.info("输出错误结果: {}", frame.getPayload());
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果: " + new String(frame.getPayload()));
                        log.info("输出结果: {}", frame.getPayload());
                    }
                    super.onNext(frame);
                }
            };
            final long[] maxMemory = {0L};

            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            ResultCallback<Statistics> statisticsResultCallback = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用" + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onStart(Closeable closeable) {

                }


                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });
            statsCmd.exec(statisticsResultCallback);

            try {
                stopWatch.start();
                boolean b = dockerClient.execStartCmd(execCreateCmdResponse.getId()).exec(execStartResultCallback)
                        // 设置最大执行时间, 防止超时
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                log.info("是否成功: {}", b);

                stopWatch.stop();
                time = stopWatch.getLastTaskTimeMillis();

                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }

            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }

        log.info("执行结果: {}", executeMessageList);

        /**
         * 5. 整理输出，构造代码执行的响应结果
         * (1) 输出结果: outputList
         * (2) 接口信息: message
         * (3) 执行状态: status
         *      1: 执行成功
         *      2: 异常
         *      3: 执行失败
         * (5) 判题信息: judgeInfo
         *    判题信息包括：程序执行信息(message)、消耗时间(time)以及消耗内存(memory)
         */
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0L;
        // 遍历所有执行信息
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                response.setMessage(errorMessage);
                response.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            if (executeMessage.getTime() != null) {
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
        }

        if (outputList.size() == executeMessageList.size()) {
            response.setStatus(1);
        }
        response.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        response.setJudgeInfo(judgeInfo);
        log.info("响应结果: {}", response);

        return response;
    }

    /**
     * 构建异常错误响应
     *
     * @param e 异常状态
     * @return 异常错误响应
     */
    private ExecuteCodeResponse createErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());
        return response;
    }


    /**
     * 执行代码示例
     *
     * @param args
     */
    public static void main(String[] args) {
        JavaDockerCodeSandBox javaDockerCodeSandBox = new JavaDockerCodeSandBox();

        String code = ResourceUtil.readStr("test/computeArgs/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("test/unSafeCode/ReadFileError.java", StandardCharsets.UTF_8);
        ExecuteCodeRequest request = ExecuteCodeRequest.builder().inputList(Arrays.asList("1 2", "3 4")).code(code).language("java").build();

        ExecuteCodeResponse response = javaDockerCodeSandBox.executeCode(request);
    }
}
